package com.android.fzmap.map;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.os.Bundle;
import android.util.Log;

import com.android.fzmap.utils.CommonHelper;

public class HttpUtil {
	/**
	 * 发送请求
	 * @param url
	 * @param method
	 * @param params
	 * @param enc
	 * @return
	 */
	public static String openUrl(String url, String method, Bundle params, String enc){
		String lat = params.getString("lat");
		String lng = params.getString("lng");
		return doGet(url , lat, lng);
	}
	
	
	public static String doGet(String url,String lat, String lng) {
		StringBuffer paramStr = new StringBuffer();
		paramStr.append(url).append("?").append("lng=").append(lng).append("&").append("lat=").append(lat);

		url = paramStr.toString();
		HttpGet httpRequest = new HttpGet(url);
		String strResult = null;
		try {
			HttpClient httpClient = getHttpClient();
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				strResult = EntityUtils.toString(httpResponse.getEntity());
			} else if (httpResponse.getStatusLine().getStatusCode() == 400) {
				strResult = "error";
			} else if (httpResponse.getStatusLine().getStatusCode() == 500) {
				strResult = "error";
			} else {
				strResult = "error";
			}
		} catch (Exception e) {
			Log.d("ss", "HttpConnection.doGet() Exception " + e.getMessage());
		}
		Log.d("HttpUtil", "strResult:" + strResult);
		return strResult;
	}
	
		
	public static HttpClient getHttpClient() {
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams,
				20* 1000);
		HttpConnectionParams.setSoTimeout(httpParams,
				20* 1000);
		HttpConnectionParams.setSocketBufferSize(httpParams,
				4096);
		HttpClientParams.setRedirecting(httpParams, true);
		String userAgent = CommonHelper.getUserAgent();
		HttpProtocolParams.setUserAgent(httpParams, userAgent);
		return new DefaultHttpClient(httpParams);
	}
	/**
	 * 读取输入流，转换为String
	 * @param in
	 * @param enc
	 * @return
	 * @throws IOException
	 */
	private static String read(InputStream in, String enc) throws IOException {
		StringBuilder sb = new StringBuilder();
		BufferedReader r = null;
		if(enc != null){
			//按指定的编码读入流
			r = new BufferedReader(new InputStreamReader(in,enc), 1000);
		}else{
			//按默认的编码读入
			r = new BufferedReader(new InputStreamReader(in), 1000);
		}
		for (String line = r.readLine(); line != null; line = r.readLine()) {
			sb.append(line);
		}
		in.close();
		return sb.toString();
	}
	/**
	 * 按key-Value的方式组拼请求参数
	 * 参数内通过“=”连接，参数间通过“&”来连接
	 * @param parameters
	 * @return
	 */
	public static String encodeUrl(Bundle parameters) {
		if (parameters == null)
			return "";
		StringBuilder sb = new StringBuilder();
		//因为第一个参数和URL之间是通过"?"来连接的
		boolean first = true;
		for (String key : parameters.keySet()) {
			if (first)
				first = false;
			else
				sb.append("&");
			sb.append(key + "=" + parameters.getString(key));
		}
		return sb.toString();
	}
	/**
	 * 把数据post到服务器，获取返回的结果
	 * 
	 * @param uriAPI
	 *            ： API 所在的路径
	 * @param params
	 *            ： 传递的数据
	 */
	public static String postToServer(String uriAPI, List<NameValuePair> params) {
		/* 建立HTTPost对象 */
		HttpPost httpRequest = new HttpPost(uriAPI);
		
		try {
			/* 添加请求参数到请求对象 */
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			/* 发送请求并等待响应 */
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequest);
			/* 若状态码为200 ok */
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				return EntityUtils.toString(httpResponse.getEntity());

			} else {
				return "Error Response: "
						+ httpResponse.getStatusLine().toString();
			}
		} catch (Exception e) {
			return "post failure :caused by-->" + e.getMessage().toString();
		}

	}
}
